﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using WMS.FC.Domain.DomainObject.System;
using WMS.FC.Domain.DomainObject.Technology;
using WMS.FC.Domain.PersistenceObject.Business;
using WMS.FC.Domain.Repository;
using WMS.FC.Domain.Service.System;
using WMS.FC.Domain.Service.Technology.Interface;

namespace WMS.FC.Domain.Service.Technology
{
    public class EditTechnologyRouteService : ServiceBase, IEditTechnologyRouteService
    {
        protected readonly ITechnologyRepository technologyRepository;

        public EditTechnologyRouteService(
            ILogger<ServiceBase> logger,
            IOptions<WmsSettings> options,
            IMapper mapper,
            ITechnologyRepository technologyRepository)
            : base(logger, options, mapper)
        {
            this.technologyRepository = technologyRepository;
        }

        public async Task<ActionResultBase> EditTechnologyRoute(TechnologyRouteDO? dO, UserInfo userInfo)
        {
            var result = new ActionResultBase("编辑工艺路径");
            try
            {
                if (dO == null)
                    return result.ArgumentError("工艺路径数据不能为空");

                var count = await technologyRepository.GetCount<TechnologyRoutePO>(entity => entity.Code == dO.Code && entity.Id != dO.Id);
                if (count > 0)
                    return result.ArgumentError($"编码:{dO.Code},工艺路径已存在");

                var technologyRoutePO = await technologyRepository.FindById<TechnologyRoutePO>(dO.Id);
                if (technologyRoutePO == null)
                    return result.BusinessError($"ID:{dO.Id},工艺路径数据未找到");

                count = await technologyRepository.GetCount<TechnologyRouteProcessPO>(entity => entity.TechnologyRouteCode == technologyRoutePO.Code);
                if (count > 0 && dO.Code != technologyRoutePO.Code)
                    return result.BusinessError($"编码:{technologyRoutePO.Code},工艺路径已添加工序,不能修改编码");

                mapper.Map(dO, technologyRoutePO);
                count = await technologyRepository.Update(technologyRoutePO, userInfo);

                if (count == 0)
                    return result.DbError("编辑工艺路径异常");

                result.Message = "编辑数据成功";
            }
            catch (Exception ex)
            {
                return result.Exception(ex);
            }

            return result;
        }
    }
}
